package com.cy.sys.service.realm;

import com.cy.sys.dao.SysMenuDao;
import com.cy.sys.dao.UserDao;
import com.cy.sys.pojo.sysUserPojo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ShrioUserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    @Autowired
    private SysMenuDao menu;
    @Autowired
    private UserDao user;
    @Override
    public void setCredentialsMatcher(
            CredentialsMatcher credentialsMatcher){
        HashedCredentialsMatcher cm=new HashedCredentialsMatcher();
        cm.setHashAlgorithmName("MD5");
        cm.setHashIterations(1);
        super.setCredentialsMatcher(cm);
        //此方法完成认证数据获取，系统会将认证信息传递管理器，有管理器完成认证

    }
//=================================有问题=============================================
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken up= (UsernamePasswordToken) authenticationToken;
      String username=up.getUsername();
        sysUserPojo users=user.findByUserName(username);
        if(users==null)
            throw new UnknownAccountException("用户不存在");
        if(users.getValid()==0)
            throw new LockedAccountException("用户被禁用");
        //封装用户信息
        ByteSource bySalt=ByteSource.Util.bytes(users.getSalt());
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
                users,
                users.getPassword(),
                bySalt,
                getName());

        return info;
        //此值返回给认证管理器
    }
}
